package com.intexh.quickandroid.module.chat;

import android.content.Context;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.intexh.quickandroid.BuildConfig;
import com.intexh.quickandroid.module.chat.ChatManager.EasemobManager;
import com.intexh.quickandroid.module.chat.ChatManager.EasemobUtil;
import com.intexh.quickandroid.module.chat.bean.UserInfo;
import com.intexh.quickandroid.module.chat.util.DbHelper;
import com.intexh.quickandroid.utils.LogCatUtil;
import com.intexh.quickandroid.utils.ValidateUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Frank on 2017/4/24.
 * 聊天资源控制器
 */

public class ChatHelper {
    private static Context mAppContext;
    private static UserInfo mUserInfo;

    public static ExecutorService persistenceExecutorService;
    private static ExecutorService multiThreadExecutorService;
    private static ChatHelper instance;
//    private CallReceiver callReceiver;
    public boolean isVoiceCalling;  //是否正在语音通话
    public boolean isVideoCalling;  //是否正在视频通话
    private boolean isChatLoginNow;  //是否正在登录环信

    public synchronized static ChatHelper getInstance() {
        if (instance == null) {
            instance = new ChatHelper();
        }
        return instance;
    }

    public void init(Context appContext,UserInfo userInfo){
        mAppContext = appContext;
        mUserInfo = userInfo;
        persistenceExecutorService = Executors
                .newSingleThreadExecutor();
        //初始化 环信
        EMOptions options = new EMOptions();
        EMClient.getInstance().init(appContext, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(BuildConfig.IS_DEBUG);
        //初始化数据库 优化数据库（替换）
        DbHelper.init(appContext);

        /**初始化语音视频通话 需要引用完整的库 有用不能删
         1.取消注释 VoiceCallActivity VideoCallActivity CallActivity CallReceiver
         2.开启AndroidManifest.xml VoiceCallActivity VideoCallActivity 注册
         3.取消 AppChatFragment 内startVoiceCall startVideoCall方法注释 */
/*        IntentFilter callFilter = new IntentFilter(EMClient.getInstance().callManager().getIncomingCallBroadcastAction());
        if(callReceiver == null){
            callReceiver = new CallReceiver();
        }
        appContext.registerReceiver(callReceiver, callFilter);*/

        EasemobUtil.INSTANCE.init();

    }

    public Context getAppContext(){
        return mAppContext;
    }

    public UserInfo getUserInfo(){
        return mUserInfo;
    }

    public void updateUserInfo(UserInfo userInfo){
//        LogCatUtil.e("frank","更新环信信息： "+userInfo.toString());
        mUserInfo = userInfo;
    }

    //环信登陆
    public void login(String chat_uid, String chat_password){
        if(ValidateUtils.isValidate(chat_uid)&& ValidateUtils.isValidate(chat_password)){
            if(!isChatLoginNow){ //同一时间只能一次登录
                isChatLoginNow=true;
                EasemobManager.login(chat_uid,chat_password,new EMCallBack() {
                    @Override
                    public void onError(int arg0, final String errorMsg) {
                        isChatLoginNow=false;
                        LogCatUtil.e("frank", "环信登录失败: chatId="+ chat_uid + "  chatPwd=" + chat_password +"\n"+ errorMsg);
                    }

                    @Override
                    public void onProgress(int arg0, String arg1) {
                        isChatLoginNow=true;
                        LogCatUtil.e("frank", "环信登录中..."+arg0);
                    }

                    @Override
                    public void onSuccess() {
                        isChatLoginNow=false;
                        LogCatUtil.e("frank", "环信登录成功");
                    }
                });
            }
        }else{
            LogCatUtil.e("frank","环信账号不可用,无法登陆 "+chat_uid+" : "+chat_password);
        }
    }

    public boolean isLogin() {
        return EMClient.getInstance().isConnected();
    }


    //退出环信登陆
    public void loginOut(){
        EasemobManager.logout();
    }

    //线程池
    public ExecutorService getExecutor(int size) {
        if (size <= 1) {
            return persistenceExecutorService;
        } else {
            if (multiThreadExecutorService == null) {
                multiThreadExecutorService = Executors.newFixedThreadPool(5);
            }
            return Executors.newFixedThreadPool(5);
        }
    }
}
